import db, {users} from '../../database/lowDB/connectDb.js';

import {unioformDateTransform,autoIncreamentKey} from '../../utils/index.js'


class usersModel {
    constructor() {
        this.tableName = 'users';
    }
    
    // 获取所有用户
    async getAllUsers() {
        return users;
    }
    
    // 根据用户名和密码获取用户
    async getUserByCredentials(username, password) {
        return users.find(user => user.userName === username && user.password === password);
    }


    // 根据用户名，手机号，或者用户id获取用户信息
    async getUserByUniqueIdentifier(identifier) {
        // identifier 可以是用户名、手机号或用户ID，或者它们的组合
        const {userId,userName,phone} = identifier;
        return  users.find((item)=>{
            return (userId ? userId : item.id) === item.id && 
                (userName ? userName : item.userName) === item.userName && 
                (phone  ? phone : item.phone) === item.phone
        })
    }



    // 更新用户信息
    async updateUser(id, userData) {
        const index = users.findIndex(user => user.id === id);
        if (index !== -1) {
            users[index] = {...users[index], ...userData};
            db.write();
            return true;
        }
        return null;
    }

    //新增用户
    async addUser(userData) {
         const newUser = {
            id: autoIncreamentKey(users), 
            userName:userData.userName,
            password:userData.password,
            phone:userData.phone,
            randomQuestion:userData.randomQuestion,
            roles:[],
            lastLoginTime:"",
            createTime:unioformDateTransform(new Date()),
            currentRoleCode:""
        };
        users.unshift(newUser);
        db.write()
        return true;
    }


    /*
    
    // 删除用户
    async deleteUser(id) {
        const index = users.findIndex(user => user.id === id);
        if (index !== -1) {
            const deletedUser = users.splice(index, 1);
            db.write();
            return deletedUser[0];
        }
        return null;
    }

    */
}   

export default new usersModel();